package net.yihang.service;

import sun.misc.ProxyGenerator;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;

public class ProxyTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 1. 类加载器
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        // 2. 接口
        Class[] interfaces = new Class[]{UserService.class};
        // 3. 调用处理器
        InvocationHandler handler = (proxy, method, arguments) -> {
            System.out.println(method);
            return null;
        };
        Proxy.newProxyInstance(cl, interfaces, handler);

        String className = "UserServiceProxy";
        byte[] bytes = ProxyGenerator.generateProxyClass(className, interfaces);

        /*
            当调用自定义类加载的loadClass方法时：
            自定义类加载器首先会找到上层类加载器来查找UserServiceProxy类
            当然这个例子里，jvm中本没有UserServiceProxy类，因此就调用自定义类加载器findClass方法
            findClass方法内部使用defineClass方法完成类加载
        */
        ClassLoader classLoader = new ClassLoader() {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                return this.defineClass(name, bytes, 0, bytes.length);
            }
        };

        Class<?> clazz = classLoader.loadClass(className);

        UserService service = (UserService)
                clazz.getConstructor(InvocationHandler.class).newInstance(handler);
        service.find1();
    }
}
